//
//  BanBu_TransmitViewController.m
//  BanBu
//
//  Created by Wang Xj on 13-8-23.
//
//

#import "BanBu_TransmitViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_FriendListCell.h"
#import "BanBu_NavButton.h"
#import "BanBu_FriendListController.h"
#import "BanBu_TransmitCell.h"

@interface BanBu_TransmitViewController ()

@end

@implementation BanBu_TransmitViewController
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.searchBl = NO;
    MyAppDataManager.transmitController = self;
    self.talkArray = [NSMutableArray arrayWithCapacity:30];
    self.chooseDic = [NSMutableDictionary dictionaryWithCapacity:20];
    
    self.title = NSLocalizedString(@"choosePerson", nil);
    
    self.talkArray= [MyAppDataManager getUserID:@"600"];
    self.pnameDic = [MyAppDataManager getPnameArray:self.talkArray];
    
    if (self.talkArray.count)//如果不为空则获取个人资料，否则不显示最近列表
    {
        self.talkArray = [MyAppDataManager getPersonalDataOfUseridFromTalk:self.talkArray];
    }
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
    CGFloat btnLen1 = [NSLocalizedString(@"choose", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    self.chooseButton = [[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal] autorelease];
    self.chooseButton.position = ButtonPositionRight;
    self.chooseButton.frame=CGRectMake(0, 0, btnLen1+20, 30);
    self.chooseButton.tag = 101;
    [self.chooseButton addTarget:self action:@selector(setEditing:animated:) forControlEvents:UIControlEventTouchUpInside];
    [self.chooseButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    [self.chooseButton setTitle:NSLocalizedString(@"choose", nil) forState:UIControlStateNormal];
    self.chooseButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:self.chooseButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
    
    //加载搜索框

    self.searchView = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 40)] autorelease];
    self.searchView.delegate = self;
    
    //2
    UISearchDisplayController * searchDisPlay = [[UISearchDisplayController alloc]initWithSearchBar:self.searchView contentsController:self];
    searchDisPlay.delegate = self;
    searchDisPlay.searchResultsDelegate = self;
    searchDisPlay.searchResultsDataSource = self;
    
    self.tableView.tableHeaderView = self.searchView;
   
    [self setEditing:YES animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dismissTKLoading
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"sendS", nil) activityAnimated:NO duration:1.2f];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dismiss
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:1];
}


//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
	[super setEditing:!self.editing animated:YES];
    
    if(self.editing)
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        self.chooseButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [self.chooseButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    }
    else
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"choose", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        self.chooseButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [self.chooseButton setTitle:NSLocalizedString(@"choose", nil) forState:UIControlStateNormal];
    }
    
    if(self.chooseDic.count)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            //在数据库中保存转发的聊天记录
            
            //useridAndChatIDDic：userid与chatid一一对应
            NSDictionary * useridAndChatIDDic = [MyAppDataManager saveTransmitMsg:self.msgDic andUserIDList:self.chooseDic];
            
            NSArray *mapArr = typeArrDefine;
            //[NSArray arrayWithObjects:@"text",@"image",@"location",@"sound",@"emi",@"hints",@"video",@"magicGif",@"specialApp",nil];
            
            NSDictionary *saysDic = [NSDictionary dictionaryWithObjectsAndKeys:VALUE(KeyContent, self.msgDic),KeyContent,[mapArr objectAtIndex:[VALUE(KeyType, self.msgDic) integerValue]],KeyType,VALUE(KeyShowFrom, self.msgDic),KeyShowFrom,[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex],KeyBubbleID,VALUE(KeyThumbnail, self.msgDic),KeyThumbnail,nil];
            
            NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:5];
            [sendDic setValue:saysDic forKey:KeySays];
            [sendDic setValue:useridAndChatIDDic forKey:KeyChatid];
            [sendDic setValue:[self.chooseDic.allKeys componentsJoinedByString:@","] forKey:@"touid_list"];
            [sendDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            [sendDic setValue:@"transmit" forKey:@"transmit"];
            
            //提交消息
            [AppComManager getBanBuData:BanBu_SendMessage_To_Server_V2 par:sendDic delegate:MyAppDataManager];
            
            [self performSelectorOnMainThread:@selector(dismiss) withObject:nil waitUntilDone:YES];
            //删除数组清空
            [self.chooseDic removeAllObjects];
        });
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section ==0)
    {
        return nil;
    }
    return NSLocalizedString(@"recentChat", nil);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else
    {
        if ( [tableView isEqual:self.searchDisplayController.searchResultsTableView] )
        {
            return self.searchResults.count;
        }
        else
        {
            return self.talkArray.count;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        static NSString *CellIdentifier1 = @"Cell1";
        BanBu_TransmitCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if (cell == nil)
        {
            cell = [(BanBu_TransmitCell *)[[BanBu_TransmitCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier1] autorelease];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.editingAccessoryType = UITableViewCellEditingStyleNone;
        }
        cell.textLabel.text = NSLocalizedString(@"createNewChat", nil);
        return cell;
    }
    else
    {
        static NSString *CellIdentifier2 = @"Cell2";
        BanBu_FriendListCell *cell = (BanBu_FriendListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        
        if (cell == nil)
        {
            cell = [[[BanBu_FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        NSDictionary * friendInfoDic = nil;
        
        if ([tableView isEqual:self.searchDisplayController.searchResultsTableView] )
        {
            NSString * pName = [self.searchResults objectAtIndex:indexPath.row];
            friendInfoDic = [self.pnameDic valueForKey:pName];
        }
        else
        {
            NSDictionary * infoDic = [self.talkArray objectAtIndex:indexPath.row];
            friendInfoDic = [infoDic valueForKey:keyPersonalInfo];
        }
        
        [cell setAvatar:[friendInfoDic valueForKey:KeyUface]];
        [cell setName:[friendInfoDic valueForKey:KeyPname]];
        
        NSString * indexPathRow = [self.chooseDic valueForKey:[friendInfoDic valueForKey:KeyFromUid]];
        
        if (indexPathRow)
        {
            [cell setChecked:YES];
        }
        else
        {
            [cell setChecked:NO];
        }

        return cell;
    }
}


#pragma mark - Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0)
    {
        [self createNewChat:nil];
    }
    else
    {
        if(self.tableView.editing || self.searchBl)
        {
            NSString * userid = @"";
            if (self.searchBl)
            {
                NSString * pName = [self.searchResults objectAtIndex:indexPath.row];
                userid = [[self.pnameDic valueForKey:pName] valueForKey:KeyFromUid];
            }
            else
            {
                userid = [[self.talkArray objectAtIndex:indexPath.row] valueForKey:KeyFromUid];
            }

            
            BOOL isChecked = YES ;
            
            if (![self.chooseDic valueForKey:userid])
            {
                isChecked = NO;
            }
            
            if(!isChecked)
            {
                if (self.chooseDic.count>4)
                {
                    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"theLargeNumber", nil) activityAnimated:NO duration:2];
                    return;
                }

                [self.chooseDic setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:userid];
            }
            else
            {
                [self.chooseDic removeObjectForKey:userid];
            }
            
            BanBu_FriendListCell *cell = (BanBu_FriendListCell *)[tableView cellForRowAtIndexPath:indexPath];
            
            [cell setChecked:!isChecked];

            [self.searchDisplayController setActive:NO animated:YES];
        }
    }
}

-(void)createNewChat:(UITapGestureRecognizer *)tap
{
    BanBu_FriendListController * friendListController= [[BanBu_FriendListController alloc]init];
    friendListController.msgDic = self.msgDic;
    friendListController.chatController = _chatController;
    
    [self.navigationController pushViewController:friendListController animated:YES];
    [friendListController release];
}

#pragma mark - UISearchBarDelegate

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    
    self.searchResults = [self.pnameDic.allKeys filteredArrayUsingPredicate:resultPredicate];
}

#pragma mark - 

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    self.searchBl = YES;
    UISearchBar *searchBar = self.searchDisplayController.searchBar;
    [searchBar setShowsCancelButton:YES animated:YES];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    self.searchBl = NO;
    [self.tableView reloadData];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]  objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    return(YES);
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:searchOption]];
    
    return(YES);
}

-(void)dealloc
{
    MyAppDataManager.transmitController = nil;
    
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0];
    [_talkArray release],_talkArray = nil;
    [_chooseButton release],_chooseButton = nil;
    [_chooseDic release],_chooseDic = nil;
    [_msgDic release],_msgDic = nil;
    [_searchView release];
    [_pnameDic release];
    [_searchResults release];
    [super dealloc];
}

@end
